package com.hexb.core.utils;

import org.apache.log4j.Logger;

import java.util.HashMap;
import java.util.Map;

public class MapBuilder<K, V> {

    private static final Logger logger = Logger.getLogger(MapBuilder.class);

    private Map<K, V> map;


    private MapBuilder() {
        this.map = new HashMap<>();
    }

    private MapBuilder(K k, V v) {
        this.map = new HashMap<>();
        if (null != k && null != v) {
            map.put(k, v);
        }
    }

    @SuppressWarnings("unchecked")
    private MapBuilder(K k, V v, Class<? extends Map> clazz) {
        try {
            this.map = clazz.newInstance();
            if (null != k && null != v) {
                map.put(k, v);
            }
        } catch (IllegalAccessException | InstantiationException e) {
            logger.error("builder instance by " + clazz.getName() + "error : " + e.getMessage());
        }
    }

    @SuppressWarnings("unused")
    public MapBuilder<K, V> build(K key, V value) {
        if (null == map) {
            map = new HashMap<>();
        }
        if (null != key && null != value) {
            map.put(key, value);
        }
        return this;
    }

    public Map<K, V> map() {
        return map;
    }

    static public <K, V> MapBuilder<K, V> create() {
        return new MapBuilder<>();
    }

    static public <K, V> MapBuilder<K, V> create(K k, V v) {
        return new MapBuilder<>(k, v);
    }

    static public <K, V> MapBuilder<K, V> create(K k, V v, Class<? extends Map<K, V>> clazz) {
        return new MapBuilder<>(k, v, clazz);
    }
}
